import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:scoped_model/scoped_model.dart';
import 'package:test_flutter/cache/UserDataCache.dart';
import 'package:test_flutter/constant/resources.dart';
import 'package:test_flutter/dio/DioUtil.dart';
import 'package:test_flutter/model/response/user_model.dart';
import 'package:test_flutter/model/scoped_model/main_model.dart';
import 'package:test_flutter/pages/CardListPage.dart';
import 'package:test_flutter/pages/DryingPage.dart';
import 'package:test_flutter/pages/LanguagePage.dart';
import 'package:test_flutter/pages/LoginPage.dart';
import 'package:test_flutter/pages/NewsPage.dart';
import 'package:test_flutter/pages/PersonalPage.dart';
import 'package:test_flutter/pages/LaundryPage.dart';
import 'package:image_picker/image_picker.dart';
import 'package:test_flutter/pages/edite_info.dart';
import 'package:test_flutter/utils/ToastUtil.dart';
import 'package:test_flutter/utils/common_utils/CustomLocalizations.dart';
import 'package:test_flutter/utils/factory/Fit.dart';
import 'package:image_cropper/image_cropper.dart';
import 'package:test_flutter/dio/Api.dart';

class HomePage extends StatefulWidget {
  final String title;

  HomePage(this.title); // 用来储存传递过来的值

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with SingleTickerProviderStateMixin {
  TabController _controller;
  String name = '';
  File _image;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _controller = TabController(vsync: this, length: _allPages.length);
    //getUsersInfo();

    /*util.encrypted("sovell");
    util.decrypted("EIC62FyTmr+kCz1gnypJ1Q==");*/
  }

/*  getUsersInfo() async{
    UsersModel user = await UserDataCache.getInstance().getUser();
    UserDataCache.getInstance().setUser(context, user);
      print('scaledDensity:  $scaledDensity');

  }*/

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    CustomLocalizations.init(context);
    return ScopedModelDescendant<MainModel>(
      builder: (context, child, model) {
        return Scaffold(
          appBar: PreferredSize(
              child: Container(
                decoration: BoxDecoration(
                    gradient: LinearGradient(colors: [
                  Color(0xFF00E579),
                  Color(0xFF00E585),
                  Color(0xFF00E792),
                  Color(0xFF00E8A4),
                  Color(0xFF00ECBA)
                ])),
                child: AppBar(
                    centerTitle: true,
                    backgroundColor: Colors.transparent,
                    title: Container(
                      height: kToolbarHeight,
                      child: TabBar(
                        controller: _controller,
                        indicatorColor: Color(0xFFFFFFFF),
                        isScrollable: true,
                        labelStyle: TextStyle(fontSize: 15.0),
                        indicatorSize: TabBarIndicatorSize.label,
                        tabs: _allPages
                            .map((_Page page) => Tab(
                                text: CustomLocalizations.instance
                                    .getString(page.labelId)))
                            .toList(),
                      ),
                    )),
              ),
              preferredSize: Size(Fit.scaleX(1080), kToolbarHeight)),
          drawer: Drawer(
            child: Container(
              child: ListView(
                padding: EdgeInsets.only(top: 0.0),
                children: <Widget>[
                  DrawerHeader(
                    padding: EdgeInsets.zero,
                    /* padding置为0 */
                    child: Stack(children: <Widget>[
                      /* 用stack来放背景图片 */

                      Align(
                        /* 先放置对齐 */
                        alignment: FractionalOffset.center,
                        child: Container(
                          height: 90.0,
                          margin: EdgeInsets.only(left: 12.0, bottom: 12.0),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            /* 宽度只用包住子组件即可 */
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.start,
                            children: <Widget>[
                              GestureDetector(
                                onTap: () {
                                  showModalBottomSheet(
                                      context: context,
                                      builder: (BuildContext context) {
                                        return new Column(
                                            mainAxisSize: MainAxisSize.min,
                                            children: <Widget>[
                                              new ListTile(
                                                leading: new Icon(
                                                    Icons.photo_camera),
                                                title: new Text(CustomLocalizations.instance.getString(StringIds.camera)),
                                                onTap: () async {
                                                  getCameraImage();
                                                  Navigator.pop(context);
                                                },
                                              ),
                                              new ListTile(
                                                leading: new Icon(
                                                    Icons.photo_library),
                                                title: new Text(CustomLocalizations.instance.getString(StringIds.album)),
                                                onTap: () async {
                                                  getGalleryImage();
                                                  Navigator.pop(context);
                                                },
                                              ),
                                            ]);
                                      });
                                },
                                child: Align(
                                  child: CircleAvatar(
                                    radius: 40.0,
                                    backgroundImage:NetworkImage(model.AvatarUrl),
                                  ),
                                ),
                              ),
                              GestureDetector(
                                onTap: () {
                                  Navigator.of(context).push(MaterialPageRoute(
                                      builder: (BuildContext context) =>
                                          EditInfoPage()));
                                },
                                child: Container(
                                  width: Fit.scaleX(550),
                                  margin: EdgeInsets.only(left: 6.0),
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start, // 水平方向左对齐
                                    mainAxisAlignment:
                                        MainAxisAlignment.center, // 竖直方向居中
                                    children: <Widget>[
                                      Text(
                                        model.Name,
                                        style: TextStyle(
                                            fontSize: 18.0,
                                            fontWeight: FontWeight.w400,
                                            color: Colors.white),
                                      ),
                                      Text(
                                        '${model.Area} ${model.Address}',
                                        style: TextStyle(
                                            fontSize: 14.0,
                                            color: Colors.white),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ]),
                  ),
                  ListTile(
                    title: Text(CustomLocalizations.instance
                        .getString(StringIds.personalCenter)),
                    trailing: Icon(Icons.arrow_right),
                    onTap: () {
                      Navigator.of(context).push(MaterialPageRoute(
                          builder: (BuildContext context) => PersonalPage(
                              CustomLocalizations.instance
                                  .getString(StringIds.personalCenter))));
                    },
                  ),
                  Divider(), //分割线控件
                  ListTile(
                    title: Text(CustomLocalizations.instance
                        .getString(StringIds.titleLanguage)),
                    trailing: Icon(Icons.arrow_right),
                    onTap: () {
                      Navigator.of(context).push(MaterialPageRoute(
                          builder: (BuildContext context) => LanguagePage()));
                    },
                  ),
                  /* Divider(), //分割线控件
                   ListTile(
                    title:  Text(CustomLocalizations.instance
                        .getString(StringIds.about)),
                    trailing:  Icon(Icons.arrow_right),
                    onTap: () {
                      Navigator.of(context).push( MaterialPageRoute(
                          builder: (BuildContext context) =>  AboutPage(CustomLocalizations.instance
                              .getString(StringIds.about))));
                    },
                  ),*/
                  Divider(), //分割线控件
                  ListTile(
                    title: Text(CustomLocalizations.instance
                        .getString(StringIds.loginOut)),
                    onTap: () {
                      _doLoginOut();
                    },
                  ),
                  Divider(), //分割线控件
                ],
              ),
            ),
          ),
          body: TabBarView(
              controller: _controller,
              children: _allPages.map(buildTabView).toList()),
        );
      },
    );
  }

  ///相册
  Future getGalleryImage() async {
    File image = await ImagePicker.pickImage(source: ImageSource.gallery);
    if (image == null) {
      return;
    }
    print("图片路径============" + image.path);
    _cropImage(image);
  }

  ///拍照
  Future getCameraImage() async {
    File image = await ImagePicker.pickImage(source: ImageSource.camera);
    if (image == null) {
      return;
    }
    print("图片路径============" + image.path);
    _cropImage(image);
  }

  ///裁剪
  Future<Null> _cropImage(File imageFile) async {
    File croppedFile = await ImageCropper.cropImage(
        sourcePath: imageFile.path,
        ratioX: 1.0,
        ratioY: 1.0,
        maxWidth: 512,
        maxHeight: 512);
    _uploadFile(croppedFile);
    print("裁剪图片路径============" + croppedFile.path);
  }

  ///上传图片
  _uploadFile(File file) async {
    FormData formData = new FormData.from({
      "file1": new UploadFileInfo(file, "upload1.jpg"),
    });
    UsersModel user = await UserDataCache.getInstance().getUser();

    DioUtil.getInstance(context).uploadFile(Api.uploadAvatar, formData,
        (response) {
      if (response.data['code'] == 1) {
        print(response.data['data']);
        user.AvatarUrl = response.data['data']['avatarUrl'];
        UserDataCache.getInstance().setUser(context, user);
        setState(() {

        });
      } else {
        ToastUtil.showToast(response.data['msg']);
      }
    });
  }



  logout() async{
    DioUtil.getInstance(context).post(
        Api.logout,
            (response) {
          if (response.data['code'] == 1) {
            _loginOut();
          } else {
            ToastUtil.showToast(response.data['msg']);
          }

        },
        errorCallBack: (errorMsg) {
          print("error=========================:" + errorMsg);
          ToastUtil.showToast(errorMsg);

        });
  }


  ///退出登录
  void _loginOut() async {
    await UserDataCache.getInstance().loginOut();
    Navigator.of(context).pushAndRemoveUntil(
        MaterialPageRoute(builder: (context) => LoginPage('登录页')),
            (Route<dynamic> rout) => false);
  }

  Future<Null> _doLoginOut() async {
    return showDialog<Null>(
      context: context,
      barrierDismissible: true, // user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(CustomLocalizations.instance
              .getString(StringIds.loginOut)+"?"),
          actions: <Widget>[
            FlatButton(
              child: Text(CustomLocalizations.instance
                  .getString(StringIds.refuse)),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            FlatButton(
              child: Text(CustomLocalizations.instance
                  .getString(StringIds.agree)),
              onPressed: () {
                Navigator.of(context).pop();
                logout();
              },
            ),
          ],
        );
      },
    );
  }
}

Widget buildTabView(_Page page) {
  return Builder(builder: (BuildContext context) {
    switch (page.index) {
      case 0:
        return CardListPage();
        break;
/*      case 1:
        return DryingPage();
        break;

      case 2:
        return LaundryPage();
        break;*/
    }
  });
}

class _Page {
  final String labelId;
  final int index;
  _Page(this.labelId, this.index);
}

final List<_Page> _allPages = <_Page>[
  _Page(StringIds.cardManagement, 0),
  //_Page(StringIds.titleWashing, 0),
  //_Page(StringIds.titleDrying, 1),
  // _Page(StringIds.titleOther, 2),
];
